﻿Imports System.Web.UI
Imports DotNetNuke
Imports System.Web
Imports System.Web.UI.WebControls
Imports DotNetNuke.Web.Client.ClientResourceManagement
Imports System.Text
Imports DotNetNuke.Security.Roles

Namespace DotNetNuke.Modules.ActiveForums
    Partial Public Class Classic
        Inherits ForumBase

        Private fi As Forum
        Private currView As String = String.Empty

#Region "Private Members"
#If DEBUG Then
        Private _startTime As DateTime
        Private _endTime As DateTime
#End If

#End Region
#Region "Event Handlers"

        Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
#If DEBUG Then
            _startTime = DateTime.Now()
#End If
        End Sub
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            SocialGroupId = -1
            If Not Request.QueryString("GroupId") Is Nothing AndAlso IsNumeric(Request.QueryString("GroupId")) Then
                SocialGroupId = Convert.ToInt32(Request.QueryString("GroupId"))
            End If

            SetupPage()

            Try
                If Not MainSettings Is Nothing AndAlso MainSettings.InstallDate > Utilities.NullDate Then
                    If Request.IsAuthenticated And UserLastAccess = Utilities.NullDate Then

                        If Not ForumUser Is Nothing Then
                            Dim dtLastAccess As Date = Now()
                            If Not ForumUser.Profile.DateLastActivity = Utilities.NullDate Then
                                dtLastAccess = ForumUser.Profile.DateLastActivity
                            End If
                            UserLastAccess = dtLastAccess
                        End If
                    End If
                    If ForumModuleId < 1 Then
                        ForumModuleId = ModuleId
                    End If

                    Dim ctl As String = DefaultView
                    Dim opts As String = String.Empty
                    If Not Request.Params(ParamKeys.ViewType) Is Nothing Then
                        ctl = Request.Params(ParamKeys.ViewType)
                    ElseIf Not Request.Params("view") Is Nothing Then
                        ctl = Request.Params("view")
                    ElseIf Request.Params(ParamKeys.ViewType) Is Nothing And ForumId > 0 And TopicId <= 0 Then
                        ctl = Views.Topics
                    ElseIf Request.Params(ParamKeys.ViewType) Is Nothing AndAlso Request.Params("view") Is Nothing And TopicId > 0 Then
                        ctl = Views.Topic
                    ElseIf Not Settings("amafDefaultView") Is Nothing Then
                        ctl = Settings("amafDefaultView").ToString
                    End If
                    'ctl = "advanced"
                    ' If Not cbLoader.IsCallback Then
                    If Not Request.QueryString(ParamKeys.PageJumpId) Is Nothing Then
                        opts = "PageId=" & Request.QueryString(ParamKeys.PageJumpId)
                    End If
                    'End If
                    currView = ctl
                    GetControl(ctl, opts)

                    If Request.IsAuthenticated Then
                        If MainSettings.UsersOnlineEnabled Then
                            DataProvider.Instance.Profiles_UpdateActivity(PortalId, ForumModuleId, UserId)
                        End If
                    End If
                Else

                    Dim ctlPath As String = "~/DesktopModules/activeforums/controls/_default.ascx"
                    Dim ctlDefault As ForumBase = CType(LoadControl(ctlPath), ForumBase)
                    ctlDefault.ID = "ctlConfig"
                    ctlDefault.ModuleConfiguration = Me.ModuleConfiguration
                    plhLoader.Controls.Clear()
                    plhLoader.Controls.Add(ctlDefault)

                End If

                '_endTime = DateTime.Now
            Catch ex As Exception
                'Response.Write(ex.Message)
                DotNetNuke.Services.Exceptions.ProcessModuleLoadException(Me, ex)
            End Try
        End Sub

#End Region
#Region "Private Methods"
        Private Sub GetControl(ByVal view As String, ByVal options As String)
            Try
                If Not Page.IsPostBack Then
                    plhLoader.Controls.Clear()
                End If
                Dim ctl As ForumBase = Nothing
                Select Case view.ToUpperInvariant
                    Case "FORUMVIEW"
                        ctl = CType(New DotNetNuke.Modules.ActiveForums.Controls.ForumView, ForumBase)
                    Case "ADVANCED"
                        ctl = CType(LoadControl("~/desktopmodules/activeforums/advanced.ascx"), ForumBase)
                    Case Views.Topics.ToUpperInvariant, "topics".ToUpperInvariant
                        ctl = CType(New DotNetNuke.Modules.ActiveForums.Controls.TopicsView, ForumBase)
                    Case Views.Topic.ToUpperInvariant, "topic".ToUpperInvariant
                        ctl = CType(New DotNetNuke.Modules.ActiveForums.Controls.TopicView, ForumBase)
                    Case "USERSETTINGS".ToUpperInvariant
                        Dim ctlPath As String = String.Empty
                        ctlPath = "~/DesktopModules/ActiveForums/controls/af_profile.ascx"
                        If Not IO.File.Exists(Server.MapPath(ctlPath)) Then
                            ctl = CType(New DotNetNuke.Modules.ActiveForums.Controls.ForumView, ForumBase)
                        Else
                            ctl = CType(LoadControl(ctlPath), ForumBase)
                        End If
                    Case Else
                        Dim ctlPath As String = String.Empty
                        ctlPath = "~/DesktopModules/ActiveForums/controls/af_" & view & ".ascx"
                        If Not IO.File.Exists(Server.MapPath(ctlPath)) Then
                            ctl = CType(New DotNetNuke.Modules.ActiveForums.Controls.ForumView, ForumBase)
                        Else
                            ctl = CType(LoadControl(ctlPath), ForumBase)
                        End If

                End Select
                If ForumId > 0 And Not ForumInfo Is Nothing Then
                    ctl.ForumInfo = ForumInfo
                End If
                ctl.ID = view
                ctl.ForumId = ForumId
                ctl.ForumModuleId = ForumModuleId
                If ForumTabId = -1 Then
                    ForumTabId = TabId
                End If
                ctl.ForumTabId = ForumTabId
                ctl.ForumGroupId = ForumGroupId
                ctl.DefaultForumViewTemplateId = DefaultForumViewTemplateId
                ctl.DefaultTopicsViewTemplateId = DefaultTopicsViewTemplateId
                ctl.DefaultTopicViewTemplateId = DefaultTopicViewTemplateId
                ctl.UseTemplatePath = UseTemplatePath
                ctl.TemplatePath = TemplatePath
                ctl.ParentForumId = ParentForumId
                If String.IsNullOrEmpty(ForumIds) Then
                    ForumIds = UserForumsList()
                End If

                If SocialGroupId > 0 Then
                    Dim fc As New ForumController
                    ForumIds = fc.GetForumIdsBySocialGroup(PortalId, SocialGroupId)
                   
                    If String.IsNullOrEmpty(ForumIds) Then
                        Dim rc As New RoleController
                        Dim role As RoleInfo = rc.GetRole(SocialGroupId, PortalId)
                        'Create new forum
                        Dim isPrivate As Boolean = False
                        If Not role.IsPublic Then
                            isPrivate = True
                        End If
                        Dim objModules As New Entities.Modules.ModuleController
                        Dim htSettings As Hashtable = objModules.GetTabModuleSettings(TabModuleId)

                        fc.CreateGroupForum(PortalId, ModuleId, SocialGroupId, CInt(htSettings("ForumGroupTemplate").ToString()), role.RoleName & " Discussions", role.Description, isPrivate, htSettings("ForumConfig").ToString())
                        ForumIds = fc.GetForumIdsBySocialGroup(PortalId, SocialGroupId)
                    End If
                End If
                ctl.ForumIds = ForumIds
                ctl.SocialGroupId = SocialGroupId

                'ctl.PostID = PostID
                ctl.ModuleConfiguration = Me.ModuleConfiguration
                If Not options = String.Empty Then
                    ctl.Params = options
                End If
                Dim cc As New ControlsConfig
                With cc
                    .AppPath = Page.ResolveUrl("~/DesktopModules/ActiveForums/")
                    .ThemePath = Page.ResolveUrl("~/DesktopModules/ActiveForums/themes/" & MainSettings.Theme & "/")
                    .TemplatePath = .ThemePath & "templates/"
                    .SiteId = PortalId
                    .PageId = TabId
                    .InstanceId = ModuleId
                    .User = ForumUser
                    .DefaultViewRoles = Permissions.GetRoleIds(Me.ModuleConfiguration.AuthorizedViewRoles.Split(CChar(";")), PortalId)
                    .AdminRoles = Permissions.GetRoleIds(Me.ModuleConfiguration.AuthorizedEditRoles.Split(CChar(";")), PortalId)
                    .ProfileLink = "" 'GetProfileLink()
                    .MembersLink = "" ' GetMembersLink()
                End With
                Me.ControlConfig = cc
                ctl.ControlConfig = cc
                LinkControls(ctl.Controls)
                If Not plhLoader.Controls.Contains(ctl) Then
                    plhLoader.Controls.Add(ctl)
                End If
                Dim sOut As String
                sOut = vbCrLf & "<!--  © 2004 - 2012 DotNetNuke Corporation,  All Rights Reserved -->" & vbCrLf
                sOut &= "<!-- Active Forums 5.0  -->" & vbCrLf



                Dim lit As New Literal
                lit.Text = sOut
                plhLoader.Controls.Add(lit)
            Catch ex As Exception
                DotNetNuke.Services.Exceptions.ProcessModuleLoadException(Me, ex)
            End Try
        End Sub
        Private Sub LinkControls(ByVal ctrls As ControlCollection)
            For Each ctrl As Control In ctrls
                If TypeOf ctrl Is Controls.ForumRow Then
                    DirectCast(ctrl, Controls.ForumRow).UserRoles = ForumUser.UserRoles
                End If
                If TypeOf ctrl Is Controls.ControlsBase Then
                    DirectCast(ctrl, Controls.ControlsBase).ControlConfig = Me.ControlConfig
                    DirectCast(ctrl, Controls.ControlsBase).ForumData = Me.ForumData
                    DirectCast(ctrl, Controls.ControlsBase).ModuleConfiguration = Me.ModuleConfiguration
                End If
                If ctrl.Controls.Count > 0 Then
                    LinkControls(ctrl.Controls)
                End If
            Next
        End Sub
        Private Sub SetupPage()
            'Session("cpmodal_View") = Nothing
            'Session("cpmodal_options") = Nothing
            'Register theme
            If InheritModuleCSS = False Then
                ClientResourceManager.RegisterStyleSheet(Me.Page, "~/DesktopModules/ActiveForums/themes/" & MainSettings.Theme & "/module.css")
                If Not Request.QueryString("asg") Is Nothing Then
                    ClientResourceManager.RegisterStyleSheet(Me.Page, "~/DesktopModules/ActiveForums/module.css")
                End If
            End If

            Dim lang As String = "en-US"
            If Not Request.QueryString("language") Is Nothing Then
                lang = Request.QueryString("language")
            End If
            If String.IsNullOrEmpty(lang) Then
                lang = PortalSettings.DefaultLanguage
            End If
            If String.IsNullOrEmpty(lang) Then
                lang = "en-US"
            End If

            ClientResourceManager.RegisterScript(Me.Page, "~/desktopmodules/activeforums/scripts/json2009.min.js")
            ClientResourceManager.RegisterScript(Me.Page, "~/desktopmodules/activeforums/scripts/afcommon.js")
            ClientResourceManager.RegisterScript(Me.Page, "~/desktopmodules/activeforums/scripts/afutils.js")
            ClientResourceManager.RegisterScript(Me.Page, "~/desktopmodules/activeforums/active/amlib.js")

            Dim sb As New StringBuilder()
            Dim handlerURL As String = VirtualPathUtility.ToAbsolute("~/desktopmodules/activeforums/handlers/forumhelper.ashx") & "?TabId=" & TabId.ToString & "&PortalId=" & PortalId.ToString & "&moduleid=" & ModuleId & "&language=" & lang
            sb.AppendFormat("var afHandlerURL = '{0}';", handlerURL)
            sb.AppendLine("var af_imgPath = '" & VirtualPathUtility.ToAbsolute("~/DesktopModules/ActiveForums/themes/" & MainSettings.Theme) & "';")
            Dim sLoadImg As String = ""
            sLoadImg = "var afSpinLg = new Image();afSpinLg.src='" & VirtualPathUtility.ToAbsolute("~/desktopmodules/activeforums/images/spinner-lg.gif") & "';"
            sLoadImg &= "var afSpin = new Image();afSpin.src='" & VirtualPathUtility.ToAbsolute("~/desktopmodules/activeforums/images/spinner.gif") & "';"
            sb.AppendLine(sLoadImg)
            sb.AppendLine(Utilities.LocalizeControl(Utilities.GetFile(Server.MapPath("~/desktopmodules/activeforums/scripts/resx.js")), False, True))
            If HttpContext.Current.Request.IsAuthenticated And MainSettings.UsersOnlineEnabled Then
                sb.AppendLine("setInterval('amaf_pinger()',120000);")
            End If
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "afscripts", sb.ToString(), True)


            If ForumUser.Profile.IsMod Then
                ClientResourceManager.RegisterScript(Me.Page, "~/desktopmodules/activeforums/scripts/afmod.js")
                ClientResourceManager.RegisterStyleSheet(Me.Page, "~/DesktopModules/ActiveForums/active/am-ui.css")


            End If



        End Sub

#End Region
        Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
            Dim stringWriter As System.IO.StringWriter = New System.IO.StringWriter
            Dim htmlWriter As HtmlTextWriter = New HtmlTextWriter(stringWriter)
            MyBase.Render(htmlWriter)
            Dim html As String = stringWriter.ToString()
            html = Utilities.ParseToolBar(html, TabId, ForumModuleId, UserId, CurrentUserType)
            html = Utilities.LocalizeControl(html)
            writer.Write(html)
        End Sub


        Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
#If DEBUG Then
            _endTime = DateTime.Now
            Dim time As TimeSpan = _endTime.Subtract(_startTime)
            litOutput.Text = "<div style=""text-align:center;"">" & time.TotalSeconds.ToString & "</div>"
#End If
            If SocialGroupId > 0 Then
                ShowToolbar = False
            End If
            If Request.QueryString("dnnprintmode") Is Nothing And Request.QueryString("asg") Is Nothing Then
                Dim show As Boolean = True
                If currView = "grid" And Request.Params("asg") IsNot Nothing Then
                    show = False
                End If
                If Not HttpContext.Current.Items("ShowToolbar") Is Nothing Then
                    ShowToolbar = Boolean.Parse(HttpContext.Current.Items("ShowToolbar").ToString)
                End If
                If show And ShowToolbar = True Then
                    Dim lit As New LiteralControl
                    Dim sToolbar As Object = DataCache.CacheRetrieve("aftb" & ForumModuleId)
                    If sToolbar Is Nothing Then
                        sToolbar = Utilities.GetFileContent(SettingKeys.TemplatePath & "ToolBar.txt")
                        DataCache.CacheStore("aftb" & ForumModuleId, sToolbar)
                    End If
                    lit.Text = sToolbar.ToString
                    plhToolbar.Controls.Clear()
                    plhToolbar.Controls.Add(lit)
                End If

            End If
            If ForumId > 0 And TopicId < 1 And UserIsMod Then
                Dim ctl As New Controls.HtmlControlLoader
                ctl.ControlId = "aftopicedit"
                ctl.Height = "350px"
                ctl.Width = "400px"
                ctl.Name = Utilities.GetSharedResource("[RESX:TopicQuickEdit]")
                ctl.FilePath = "~/desktopmodules/activeforums/controls/htmlcontrols/quickedit.ascx"
                Me.Controls.Add(ctl)

                ctl = New Controls.HtmlControlLoader
                ctl.ControlId = "aftopicmove"
                ctl.Height = "350px"
                ctl.Width = "500px"
                ctl.Name = Utilities.GetSharedResource("[RESX:MoveTopicTitle]")
                ctl.FilePath = "~/desktopmodules/activeforums/controls/htmlcontrols/movetopic.ascx"
                Me.Controls.Add(ctl)
            End If
        End Sub
    End Class
End Namespace